/* eslint-disable @typescript-eslint/no-unused-vars */
import { Device, GatewayType } from "@/api/interface/iot";
import { getGateway, modifyGateway, saveToProduct, syncGateway, syncGetGateway } from "@/api/modules/iot/gateway";
import { getProfile } from "@/api/modules/model/profile";
import { getSchema } from "@/api/modules/model/schema";
import { serviceStart, serviceStop } from "@/api/modules/service/service";
import PageHeader from "@/components/Frame/PageHeader";
import SaveClearBtn from "@/components/Frame/save-clear-btn";
import { SchemaItem } from "@/components/JsonForm/interface";
import BasicInfo from "@/components/Sansan/Model/components/BasicInfo";
import RunningLog from "@/components/Sansan/Model/components/RunningLog.vue";
import OnlineStatus from "@/components/Sansan/OnlineStatus/OnlineStatus";
import JsonView from "@/components/Sansan/Model/develop/PrviewSchemaJson";
import DeviceConfig from "@/components/Sansan/Model/gateway/DeviceConfig";
import GatewayConfig from "@/components/Sansan/Model/gateway/GatewayConfig";
import SensorConfig from "@/components/Sansan/Model/gateway/SensorConfig";
import Navigation from "@/components/Sansan/Model/gateway/Navigation";
import SimpleInfo from "@/components/Sansan/Model/gateway/SimpleInfo";
import { GlobalStore } from "@/stores";
import { IotStore } from "@/stores/modules/iot";
import { AuthBtns, SchemaNodeKey } from "@/utils/constants";
import mittBus from "@/utils/mittBus";
import { showMsg, showTips } from "@/utils/util";
import { ElMessage } from "element-plus";
import { useRoute } from "vue-router";
import SaveToProduct from "../product/components/SaveToProduct";
import { MessageType } from "@/enums/messageEnum";
import SensorList from "@/components/Sansan/Model/device/SensorList";
import router from "@/routers";
import ExtLower from "@/components/Sansan/Model/gateway/extLower";
import { useAuthButtons } from "@/hooks/useAuthButtons";
export default defineComponent({
	setup() {
		const route = useRoute();
		const globalStore = GlobalStore();
		const iotStore = IotStore();
		let type = (route.query.type as GatewayType) || GatewayType.SoftGateway;
		// const schemaInfo = ref<SchemaItem>({});
		let menuId = route.query.menuId || GatewayType.SoftGateway;
		const gatewaySchemaInfo = ref<SchemaItem>({});
		provide(SchemaNodeKey.schema, gatewaySchemaInfo);
		provide(SchemaNodeKey.gatewaySchema, gatewaySchemaInfo);
		// const prifileInfo = ref<any>({});
		const gatewayPrifileInfo = ref<any>({});
		provide(SchemaNodeKey.profile, gatewayPrifileInfo);
		provide(SchemaNodeKey.gatewayProfile, gatewayPrifileInfo);
		const detail = reactive<any>({ detail: {} });
		provide(SchemaNodeKey.detailInfo, detail);
		const disabledMod = ref(true);
		provide(AuthBtns.disabledMod, disabledMod);
		mittBus.on("refreshGatewayDetail", () => {
			init();
		});
		const buttonsList = ref<any>([]);
		onMounted(async () => {
			init();
			// 获取页面按钮权限
			buttonsList.value = await useAuthButtons(menuId as string);
			disabledMod.value = !buttonsList.value.some((item: any) => item.path == AuthBtns.pathMod);
		});
		const init = async () => {
			await initIotData();
			// initProfile();
			// initSchema();
			await initGatewayProfile();
			await initGatewaySchema();
		};
		//初始化设备信息
		const initIotData = async () => {
			let { result, code } = await getGateway({ idSn: route.query.sn as string }, type);
			if (code == 200) {
				detail.detail = result;
				detail.detail.location = detail.detail.location || {};
			} else {
				showMsg("未找到相关数据", MessageType.error);
				timeOut.value = setTimeout(() => {
					router.go(-1);
				}, 3000);
			}
		};
		//未找到设备数据时三秒后返回上级页面
		let timeOut = ref();
		//销毁定时器
		onBeforeUnmount(() => {
			clearInterval(timeOut.value);
			timeOut.value = "";
		});
		// const initSchema = async () => {
		// 	const { result } = await getSchema({ idSn: route.query.sn });
		// 	schemaInfo.value = result.schema;
		// };
		// const initProfile = async () => {
		// 	const { result } = await getProfile({ idSn: route.query.sn });
		// 	prifileInfo.value = result;
		// };
		const initGatewaySchema = async () => {
			const { result } = await getSchema({ idSn: detail.detail.sn });
			gatewaySchemaInfo.value = result.schema;
		};
		const initGatewayProfile = async () => {
			const { result } = await getProfile({
				idSn: detail.detail.sn
			});
			gatewayPrifileInfo.value = result;
		};

		const currNav = ref<string>("");
		const basicDialog = reactive({
			title: "修改设备基本信息",
			visible: false
		});
		const changeNav = (nav: string) => {
			currNav.value = nav;
		};
		const submitBasic = async () => {
			let { success } = await modifyGateway({ ...detail.detail }, type);
			if (success) {
				ElMessage.success("修改网关成功");
				basicDialog.visible = false;
				initIotData();
			} else {
				ElMessage.error("修改网关失败！");
			}
		};
		//上传网关程序
		const uploadParam = reactive({
			data: { instanceId: "" },
			headers: { Authentication: "" }
		});
		const beforeUpload = () => {
			uploadParam.data.instanceId = detail.detail.sn;
			uploadParam.headers.Authentication = globalStore.token;
			return true;
		};
		const uploadGatewaySuccess = async (res: any) => {
			let { code } = res;
			showTips(code, "程序更新");
		};
		const uploadGatewayError = async () => {
			showMsg("程序更新失败", false);
		};
		//停止、启动网关
		const operateGateway = async (type: string) => {
			let res;
			if (type == "start") {
				res = await serviceStart({ instanceId: detail.detail.sn });
			} else {
				res = await serviceStop({ instanceId: detail.detail.sn });
			}
			let ok = showTips(res.code, type == "start" ? "启动网关" : "停止网关");
			if (ok) {
				await init();
			}
		};

		//按钮事件
		const handleFn = function (fn: String, row?: any) {
			switch (fn) {
				case "saveToProduct":
					saveToProductDialog.formData.id = detail.detail.sn;
					saveToProductDialog.formData.name = detail.detail.name;
					saveToProductDialog.visible = true;
					break;
				case "sync":
					syncGateway({ idSn: detail.detail.sn }).then(res => {
						showTips(res.code, "下发同步网关配置命令");
					});
					break;
				case "syncGet":
					syncGetGateway({ idSn: detail.detail.sn }).then(res => {
						showTips(res.code, "下发参数设置命令");
						init();
					});
					break;
			}
		};
		const saveToProductDialog = reactive<any>({
			visible: false,
			formData: {
				id: "",
				name: "",
				type: GatewayType.Device
			}
		});

		const submitToProduct = async (data: Device.ReqProduct) => {
			let { code } = await saveToProduct(data);
			let ok = showTips(code, "设备另存为产品");
			if (ok) saveToProductDialog.visible = false;
		};
		return () => {
			return (
				<div class="">
					{iotStore.isMaxDetail ? null : (
						<>
							<PageHeader
								showBackText={false}
								v-slots={{
									operate: () => {
										return (
											<>
												{menuId == AuthBtns.softGateway && (
													<div class="pr-4">
														<el-upload
															headers={uploadParam.headers}
															show-file-list={false}
															action="/api/service/bin/upload"
															before-upload={() => beforeUpload()}
															on-success={uploadGatewaySuccess}
															on-error={uploadGatewayError}
															name="file"
															data={uploadParam.data}
														>
															<el-button class="iconfont iconbx-upload">更新程序</el-button>
														</el-upload>
													</div>
												)}
												<el-button class="iconfont iconbx-skip-next-circle" onClick={() => handleFn("saveToProduct")}>
													另存为产品
												</el-button>
												<el-button class="iconfont iconbx-skip-next-circle" onClick={() => handleFn("sync")}>
													下发配置
												</el-button>
												<el-button class="iconfont iconbx-skip-next-circle" onClick={() => handleFn("syncGet")}>
													获取配置
												</el-button>
												{menuId == AuthBtns.softGateway && (
													<>
														<el-button class="iconfont iconbx-skip-next-circle" onClick={() => operateGateway("start")}>
															启动
														</el-button>
														<el-button class="iconfont iconbx-stop-circle mr-1" onClick={() => operateGateway("end")}>
															停止
														</el-button>
													</>
												)}
												{!disabledMod.value && <SaveClearBtn v-model={basicDialog.visible} onSubmit={() => submitBasic()} />}
											</>
										);
									}
								}}
							>
								<span>{detail.detail.name || detail.detail.sn}</span>
								<OnlineStatus class="ml-4 mr-4" v-model={detail.detail.onlineStatus} />
								<el-link
									class="iconfont iconbx-sync ml-2"
									type="primary"
									onClick={() => {
										init();
									}}
								>
									刷新
								</el-link>
							</PageHeader>

							<SaveToProduct
								title="另存为产品"
								v-model:visible={saveToProductDialog.visible}
								formData={saveToProductDialog.formData}
								onSubmit={(data: Device.ReqProduct) => {
									submitToProduct(data);
								}}
							></SaveToProduct>
						</>
					)}
					{Object.keys(gatewaySchemaInfo.value).length ? (
						<>
							{iotStore.isMaxDetail ? null : (
								<div class="mb-4 p-4 bg-white ">
									{/* 基本信息：名称、分组、网关 */}
									<SimpleInfo visible={basicDialog.visible} />
								</div>
							)}

							<div class="iot-detail-content">
								{/* 导航分类：基本信息、设备参数、设备模型、设备日志 */}
								<Navigation onChange={val => changeNav(val)} />

								<div class="bg-white detail-type-detail">
									{/*基本信息*/}
									{currNav.value == SchemaNodeKey.basic ? <BasicInfo type={GatewayType.Gateway} /> : null}
									{/*网关	配置*/}
									{currNav.value == SchemaNodeKey.extNavGatewayConfig ? <GatewayConfig /> : null}
									{/*设备配置信息--接入地址、接入端口*/}
									{/* {currNav.value == SchemaNodeKey.extNavDeviceConfig ? <DeviceConfig /> : null} */}
									{/*设备变量配置--变量字段描述*/}
									{/* {currNav.value == SchemaNodeKey.extNavSensorConfig ? <SensorConfig /> : null} */}
									{/* 下位机 */}
									{currNav.value == SchemaNodeKey.extLower ? <ExtLower /> : null}
									{/*设备模型*/}
									{currNav.value == SchemaNodeKey.sensor ? <SensorList /> : null}
									{/*运行日志*/}
									{currNav.value == SchemaNodeKey.extRunningLog ? <RunningLog instanceId={detail.detail.sn} /> : null}
									{/*模型定义*/}
									{currNav.value == SchemaNodeKey.extDevelop ? <JsonView type={GatewayType.Gateway} /> : null}
								</div>
							</div>
						</>
					) : (
						""
					)}
				</div>
			);
		};
	}
});
